<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="小说标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入小说标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="小说内容" prop="content">
        <el-input v-model="queryParams.content" placeholder="请输入小说内容" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="小说作者" prop="author">
        <el-input v-model="queryParams.keyword" placeholder="请输入小说作者" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="小说作者" prop="author">
        <el-input v-model="queryParams.author" placeholder="请输入小说作者" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否原创" prop="isOriginal">
        <el-select v-model="queryParams.isOriginal" placeholder="请选择是否原创">
          <el-option v-for="item in dict.type.novel_type" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['novel:novel:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['novel:novel:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['novel:novel:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['novel:novel:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleImport"
          v-hasPermi="['novel:novel:add']">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="novelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="小说标题" align="center" prop="title" />  -->
      <el-table-column prop="title" label="小说标题">
        <template slot-scope="scope">
          <span v-html="scope.row.title"></span>
        </template>
      </el-table-column>
      <el-table-column label="小说作者" align="center" prop="author" />
      <el-table-column label="小说预览" align="center" prop="preview" width="500" />
      <el-table-column label="是否原创" align="center" prop="isOriginal" width="50">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.novel_type" :value="scope.row.isOriginal" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['novel:novel:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['novel:novel:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />


    <!-- 添加或修改小说模块对话框 -->
    <el-dialog :title="title" :visible.sync="open" fullscreen append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="小说标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="小说作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入小说作者" />
        </el-form-item>
        <el-form-item label="小说预览" prop="preview">
          <el-input v-model="form.preview" type="textarea" placeholder="请输入小说预览" />
        </el-form-item>
        <el-form-item label="是否原创" prop="isOriginal">
          <el-select v-model="form.isOriginal" placeholder="请选择是否原创">
            <el-option v-for="item in isOriginalOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="小说内容" prop="centent">
          <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
          <Editor style="height: 500px; overflow-y: hidden;" v-model="form.content" :defaultConfig="editorConfig"
            :mode="mode" @onCreated="onCreated" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入小说 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" accept=".zip, .txt, .docx, .doc" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :data="upload" :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>可以上传zip,txt,word</span>
          <el-form ref="elForm" :model="upload" :rules="rules" size="medium" label-width="100px">
            <el-form-item label="作者" prop="author">
              <el-input v-model="upload.author" placeholder="请输入作者" :maxlength="11" show-word-limit clearable
                prefix-icon='el-icon-mobile' :style="{ width: '100%' }"></el-input>
            </el-form-item>
            <el-form-item label="是否原创" prop="isOriginal" required>
              <el-switch v-model="upload.isOriginal" :active-value='1' :inactive-value='0'></el-switch>
            </el-form-item>
          </el-form>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入小说进度 -->
    <el-dialog :title="uploadSchedule.title" :visible.sync="uploadSchedule.open" width="400px" append-to-body>
      <el-progress :text-inside="true" :stroke-width="24" :percentage="uploadSchedule.percentage"
        status="success"></el-progress>
      <span>共计小说{{ uploadSchedule.total }}本，剩余{{ uploadSchedule.residue }}本</span>
    </el-dialog>
  </div>
</template>

<script>
import { listNovel, getNovel, delNovel, addNovel, updateNovel, getImportNovelSchedule } from "@/api/novel/novel";
import '@wangeditor/editor/dist/css/style.css';
import { getToken } from "@/utils/auth";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
export default {
  components: { Editor, Toolbar },
  name: "Novel",
  dicts: ['novel_type'],
  data() {
    return {
      uploadSchedule: {
        title: "导入小说进度",
        open: false,
        percentage: 0,
        total: 0,
        residue: 0,
        key: ""
      },
      // 导入小说参数
      upload: {
        // 是否原创
        isOriginal: 0,
        // 作者
        author: "",
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/novel/novel/import"
      },
      editor: null,
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
      isOriginalOptions: [{
        value: '1',
        label: '是'
      }, {
        value: '0',
        label: '否'
      }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 小说模块表格数据
      novelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        author: null,
        isOriginal: null,
        createBy: null,
        createTime: null,
        updateTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "小说标题不能为空", trigger: "blur" }
        ],
        author: [
          { required: true, message: "小说作者不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    // setTimeout(() => {
    //   this.html = ''
    // }, 1500)
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    calculatePercentage(num1, num2) {
      // 计算并格式化百分比结果到两位小数
      const percentage = Math.floor(num1 / num2 * 100);
      return percentage;
    },
    startgetImportNovelSchedule() {
      this.importIntervalId = setInterval(async () => {
        getImportNovelSchedule(this.uploadSchedule.key).then(response => {
          if (response.data == undefined) {
            clearInterval(this.importIntervalId);
            this.uploadSchedule.residue = 0;
            this.uploadSchedule.percentage = 100;
            this.upload.isOriginal = 0;
            this.upload.author = "";
            this.getList();
          } else {
            this.uploadSchedule.residue = response.data
            this.uploadSchedule.percentage = this.calculatePercentage(this.uploadSchedule.total - response.data, this.uploadSchedule.total)
          }
        });
      }, 1000);
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.uploadSchedule.open = true
      this.uploadSchedule.key = Object.keys(response.data)[0];
      this.uploadSchedule.total = Object.values(response.data)[0];
      this.$refs.upload.clearFiles();
      this.startgetImportNovelSchedule();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    handleImport() {
      this.upload.title = "小说导入";
      this.upload.open = true;
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    /** 查询小说模块列表 */
    getList() {
      this.loading = true;
      listNovel(this.queryParams).then(response => {
        this.novelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        author: null,
        preview: null,
        isOriginal: null,
        isDeleted: null,
        createBy: null,
        createTime: null,
        updatedUser: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加小说";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getNovel(id).then(response => {
        this.form = response.data;
        this.form.isOriginal = this.form.isOriginal + ""
        this.open = true;
        this.title = "修改小说";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateNovel(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNovel(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除小说模块编号为"' + ids + '"的数据项？').then(function () {
        return delNovel(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('novel/novel/export', {
        ...this.queryParams
      }, `novel_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>